module(..., package.seeall) -- 使得文件中的函数在何处都可调用
require "pins" -- 用到了pin库，该库为luatask专用库，需要进行引用
require "sys"
require "getLbsLoc"
require "rtos"
require "uartTask"
require "utils"
require "mqtt"
require "misc"
require "audio"
require "math"
require "nvm"
require "send433RFSignal"
require "logGenerator"
require "mqttOutMsg"
require "httpTask"
-- 初始化设备参数文件
nvm.init("config.lua", true)
-- 参数初始化 magnitude:震级
local signalDowns, signalBreak, doSignalTask, sysTime, eqlog, errlog,
      alarm433Bool, alertStr = 0, false, true, "", "", "", false, ""
TTS = 1
-- 地震预警系统
-- 两个功能：1.预警系统演练（tts语音播报3遍同时报警音触发）
-- 入参：jsondata接收的预警信息
local setGpio9Fnc = pins.setup(pio.P0_9, 1) -- 静音设置（高电平静音）
local setGpio13Fnc = pins.setup(pio.P0_13, 0) -- 预警指示
local setGpio11Fnc = pins.setup(pio.P0_11, 0) -- Buzzer正常低电平，预警高电平
local setGpio17Fnc = pins.setup(pio.P0_17, 0) -- 地震预警测试音量控制，高电平为测试音量（音量小），低电平为正常音量（音量大）
-- local setGpio12Fnc = pins.setup(pio.P0_12, 0) -- 报警灯
-- 获取配置参数
local longitude, latitude, configIntensity, enable433, alertSound, emergencyLamp =
    nvm.get("longitude"), nvm.get("latitude"), tonumber(nvm.get("intensity")),
    nvm.get("enable433"), tonumber(nvm.get("alertSound")),
    tonumber(nvm.get("emergencyLamp"))

-- 获取系统时间
local function getSystemTime()
    local tClock, nowDate = os.date("*t"), ""
    nowDate = string.format("%04d-%02d-%02d %02d:%02d:%02d", tClock.year,
                            tClock.month, tClock.day, tClock.hour, tClock.min,
                            tClock.sec)
    return nowDate
end

-- 发送433信号
local function send433SignalTask(intensity2F433)
    doSignalTask = false
    setGpio9Fnc(0)
    send433RFSignal.InterruptSendMsg = true
    send433RFSignal.sendMsgTask()
    if not send433RFSignal.TimeId then
        send433RFSignal.vibrationAlarmRF433(10, intensity2F433, "0",
                                            alarm433Bool)
    end
    sys.wait(1000)
    signalDowns = 9
    while signalDowns > 0 do
        if signalDowns == 1 then alarm433Bool = true end
        if not send433RFSignal.TimeId then
            send433RFSignal.vibrationAlarmRF433(signalDowns, intensity2F433,
                                                "0", alarm433Bool)
        end
        if signalBreak then
            signalBreak = false
            signalDowns = 0
            break
        end
        sys.wait(1000)
        if signalBreak then
            signalBreak = false
            signalDowns = 0
            break
        end
        signalDowns = signalDowns - 1
    end
    setGpio9Fnc(1) -- 报警结束设置静音
    doSignalTask = true
    alarm433Bool = false
end

-- 预警声音播报任务
local function alarmVoiceTask()
    setGpio9Fnc(0)
    audio.play(TTS, "TTS", alertStr, 7)
    setGpio9Fnc(1)
end

-- 烈度转换为阈值
local function intensity2Threshold(intensity2Th)
    local threhold = 0
    if intensity2Th >= 1 and intensity2Th <= 3 then
        threhold = 1
    elseif intensity2Th > 3 and intensity2Th <= 5 then
        threhold = 2
    elseif intensity2Th > 5 and intensity2Th <= 7 then
        threhold = 3
    elseif intensity2Th > 7 then
        threhold = 4
    end
    log.info("intensity2Th:",intensity2Th,"threhold:",threhold)
    return threhold
end

-- 预警取消
local function cancel_alert_event()
    if signalDowns > 0 then signalBreak = true end
    while not doSignalTask do sys.wait(800) end
    if not send433RFSignal.TimeId then
        send433RFSignal.InterruptSendMsg = false
        send433RFSignal.sendMsgTask()
    end
end

-- 震动报警动作执行
local function vibrat_alarm_action(intensityLocal)
    if "false" == enable433 then enable433 = false end
    if "true" == enable433 then enable433 = true end
    log.info("震动报警动作执行！！")
    alertStr = "震动报警,震动报警,震动报警!"
    eqlog = eqlog .. "[" .. sysTime .. "]" .. "[震动报警信息:]" ..
                "震动烈度:" .. intensityLocal .. "\n"
    -- 地震烈度大于等于设定预警临界值则执行报警
    if intensityLocal >= configIntensity then
        if intensity2Threshold(intensityLocal) >= alertSound then
            sys.taskInit(alarmVoiceTask)
        else
            eqlog = eqlog .. "[" .. sysTime .. "]" ..
                        "[震动报警不满足报警音临界值：]" ..
                        "烈度阈值：" .. intensity2Threshold(intensityLocal) ..
                        ",报警音预设值：" .. alertSound .. "\n"
        end
        -- 433信号发送任务
        log.info("emergencyLamp:", emergencyLamp)
        if intensity2Threshold(intensityLocal) >= emergencyLamp and enable433 and
            doSignalTask then
            eqlog = eqlog .. "[" .. sysTime .. "]" ..
                        "满足震动报警发送433所需条件阀值！\n"
            sys.wait(200)
            log.info("intensity2Threshold(intensityLocal):",intensity2Threshold(intensityLocal))
            sys.taskInit(send433SignalTask, math.floor(intensityLocal))
        else
            eqlog = eqlog .. "[" .. sysTime .. "]" ..
                        "[震动报警发送433，执行发送433信号存在条件不满足]" ..
                        "烈度转阈值：" ..
                        intensity2Threshold(intensityLocal) ..
                        ",设定阈值：" .. emergencyLamp ..
                        "是否发送433:" .. tostring(enable433) .. "\n"
        end
    else
        eqlog = eqlog .. "[" .. sysTime .. "]" ..
                    "[不满足震动报警临界值：]" .. "烈度：" ..
                    intensityLocal .. ",烈度预设值：" .. configIntensity ..
                    "\n"
    end
end

-- 震动报警主逻辑
function VibrationAlarm(iiGet)
    errlog, eqlog = "", ""
    sysTime = getSystemTime()
    eqlog = eqlog .. "[震动报警事件]" .. "[" .. sysTime .. "]" ..
                "[设备位置信息:]" .. "Lng:" .. longitude .. ",Lat:" ..
                latitude .. "\n"
    log.info("iiGet >= configIntensity:", iiGet >= configIntensity)
    if iiGet >= configIntensity then
        if doSignalTask then
            log.info("Test12!")
            log.info("iiGet:",iiGet)
            sys.taskInit(vibrat_alarm_action, iiGet)
        end
    else
        cancel_alert_event()
    end
    if eqlog ~= nil and eqlog ~= false then
        logGenerator.generateLogTask(eqlog, "log")
    end
    if errlog ~= "" and errlog ~= false then
        logGenerator.generateLogTask(errlog, "log")
    end
end
